/**
 * Copyright (C) 2016 Fuzhou Rockchip Electronics Co., Ltd
 * author: hogan.wang@rock-chips.com
 *
 * This software is licensed under the terms of the GNU General Public
 * License version 2, as published by the Free Software Foundation, and
 * may be copied, distributed, and modified under those terms.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

#include "show.h"
#include "ascii_font.h"

static int show_ascii(int width,
                      int height,
                      void* dstbuf,
                      char n,
                      int x_pos,
                      int y_pos) {
  int i, j, l;
  unsigned char y = 16, u = 128, v = 128;  // black
  unsigned char *y_addr = NULL, *uv_addr = NULL;
  unsigned char *start_y = NULL, *start_uv = NULL;

  if (n < ASCII_SHOW_MIN || n > ASCII_SHOW_MAX || x_pos < 0 ||
      (x_pos + FONTX) >= width || y_pos < 0 || (y_pos + FONTY) >= height) {
    printf("error input ascii or position.\n");
    return -1;
  }

  y_addr = (unsigned char*)dstbuf + y_pos * width + x_pos;
  uv_addr = (unsigned char*)dstbuf + width * height + y_pos / 2 * width + x_pos;

  if (*y_addr > 0 && *y_addr < 50)
    y = 160;

  for (j = 0; j < FONTY; j++) {
    for (i = 0; i < FONTX / 8; i++) {
      start_y = y_addr + j * width + i * 8;
      start_uv = uv_addr + j / 2 * width + i * 8;
      for (l = 0; l < 8; l++) {
        if (ascii[n - ASCII_SHOW_MIN][j][i] >> l & 0x01) {
          *(start_y + l) = y;
          if (j % 2 == 0) {
            if ((i * 8 + l) % 2 == 0)
              *(start_uv + l) = u;
            else
              *(start_uv + l) = v;
          }
        }
      }
    }
  }

  return 0;
}

void show_string(const char* str,
                 int size,
                 int x_pos,
                 int y_pos,
                 int width,
                 int height,
                 void* dstbuf) {
  int i = 0;
  for (i = 0; i < size; i++)
    show_ascii(width, height, dstbuf, *(str + i), FONTX * i + x_pos, y_pos);
}

